/*  
* Copyright 2013-2020 Smartdot Technologies Co., Ltd. All rights reserved.  * SMARTDOT PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.  * 
*/ package com.ssm.zhou.project.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.ssm.zhou.project.dao.ProjectDao;

import com.ssm.zhou.project.entity.Project;
import com.ssm.zhou.project.exception.ProjectException;
import com.ssm.zhou.project.service.ProjectService;
import com.ssm.zhou.utils.CommonUtils;
import com.ssm.zhou.utils.ExcelUtils;

/** 
 * <p>  
 *   
 * @author <a href="mailto:zhoujb@smartdot.com.cn">周竞博</a>  * @version 1.0, 2020年6月2日 
 */
@Service
public class ProjectServiceImpl implements ProjectService {
	private static Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
	@Autowired
	private ProjectDao projectDao;
	/**
	 * 增加项目的时候先判断项目名
	 */
	@Override
	public int insertProject(Project project) {
		if(project.getProjectName() == null || project.getProjectName().trim().isEmpty()) {
			logger.error("项目名称不能为空");
			throw new ProjectException("项目名称不能为空");
		}
		if(projectDao.selectProjectByName(project.getProjectName()) != null){
			logger.error("数据库已存在此项目");
			throw new ProjectException("数据库已存在此项目");
		}	
		// 生成项目编码
		// 项目编码生成规则 业务单位_年月四位流水号
		String strBusinessUnit = project.getBusinessUnit();
		String strProjectCodePrefix = "";
		String strProjectCode = "";
		for(BusinessUnitEnum busEnum : BusinessUnitEnum.values()){
			if(busEnum.getBusinessUnit().equals(strBusinessUnit)){
				logger.info( busEnum.getProjectCode());
				strProjectCodePrefix = busEnum.getProjectCode();
			}
		}
		if("".equals(strProjectCodePrefix)) {
			logger.error("生成项目编码失败，未找到对应的匹配编码");
			throw new ProjectException("生成项目编码失败，未找到对应的匹配编码");
		}
		Integer numMaxCode  = projectDao.findMaxCode();
		System.out.println("最大编号：" + numMaxCode);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
		String prefix = format.format(new Date());
		Integer afterMaxCode = new Integer(1);
		if(numMaxCode == null ){
			strProjectCode = strProjectCodePrefix  + prefix +  "0001";
		}else{
			// 四位流水号用10000去加,加之后首位多一个1
			int tempNum = 10000 +  numMaxCode.intValue() + 1; 
			afterMaxCode = Integer.valueOf(CommonUtils.subStr(String.valueOf(tempNum), 1));
			strProjectCode = strProjectCodePrefix + prefix + CommonUtils.subStr(String.valueOf(tempNum), 1);
			
		}
		System.out.println("最终编号："+ strProjectCode);
		project.setMaxCode(afterMaxCode);
		project.setProjectCode(strProjectCode);
		// 生成主键UUID
		project.setId(CommonUtils.uuid());
		return projectDao.insertProject(project);
	}



	@Override
	public int updateProject(Project project) {

		return projectDao.updateProject(project);
	}

	@Override
	public List<Project> selectAllProject() {
	
		return projectDao.selectAllProject();
	}

	@Override
	public Project selectProjectByName(String projectName) {
		return projectDao.selectProjectByName(projectName);
	}

	@Override
	public int deleteProject(String id) {
		// TODO Auto-generated method stub
		return projectDao.deleteProject(id);
	}



	@Override
	public Project sesectProjecyById(String id) {
		return projectDao.selectProjectById(id);
	}


	@Transactional
	@Override
	public String excelImport(HttpServletRequest request, HttpServletResponse response) throws Exception{
	 	MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
	 	logger.info("=======excelImport========");
        MultipartFile file = multipartRequest.getFile("file"); 
        System.out.println("附件名："+ file.getSize());
        if(file.isEmpty()){  
            try {
                throw new Exception("文件不存在！");

            } catch (Exception e) {
                e.printStackTrace();
            	throw new RuntimeException(e);
            }  
        }  

        InputStream in =null;  
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        	throw new RuntimeException(e);
        }  

        List<List<Object>> listob = null; 
        
        	System.out.println(file.getOriginalFilename() + "====");        
				try {
					listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					throw new RuntimeException(e);
				}      
        for (int i = 0; i < listob.size(); i++) { 

           System.out.println(listob.get(i));

        }
        for (int i = 0; i < listob.size(); i++) {  
            List<Object> lo = listob.get(i);  
            Project vo = new Project(); 
            Project j = null;
//            if(i == 20) {
//            	System.out.println(10/0);
//            }
            try {
                j = projectDao.selectProjectByName(String.valueOf(lo.get(1)));        
            } catch (NumberFormatException e) {             
                System.out.println("数据库中无该条数据，新增");
            }
            
            vo.setId(CommonUtils.uuid());
            vo.setProjectName(String.valueOf(lo.get(1)));
            vo.setProjectCode(String.valueOf(lo.get(0)));
            vo.setBusinessUnit(String.valueOf(lo.get(2)));
            vo.setMaxCode(Integer.valueOf(0));
            if(j == null)
            {

            		projectDao.insertProject(vo);
                    System.out.println("susscess");
            }
            else
            {
            		projectDao.updateProject(vo);
            }

        }   

        return "文件导入成功！";
	}
	/**
	 * 模糊匹配
	 */
	@Override
	public List<Project> selectBykeyWord(String keyWord) {
		// TODO Auto-generated method stub
	
		return projectDao.selectBykeyWord(keyWord);
	}




}
 